package com.lanou.service.impl;

import com.alibaba.fastjson.JSON;
import com.lanou.entity.Commodity;
import com.lanou.entity.CookieUtils;
import com.lanou.entity.TbItem;
import com.lanou.service.CartService;
import com.lanou.utils.HttpClientUtils;
import com.lanou.utils.ShiHuiResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.Key;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class CartServiceImpl implements CartService {

    @Value("${CAT_JSON_URL}")
    private String CAT_JSON_URL;
    @Value("${CART_KEY_PREFIX}")
    private String CART_KEY_PREFIX;
    @Value("${CART_FIELD_PREFIX}")
    private String CART_FIELD_PREFIX;
    @Autowired
    private JedisPool jedisPool;

    //未登录状态下，修改商品
    public List<Commodity> updateCart(List<Commodity> commodities, Long itemId, Integer num) {
        //通过id查询商品信息
        TbItem tbItem = findItemById(itemId);
        //创建并且new一个实体类，里面是返回给前端的数据
        Commodity commodity = new Commodity();
        //吧tbItem 中需要的数据存到 商品中
        //设置商品状态， 0 为 未选商品 不参与结算， 1为已选商品 参与结算
        //默认 为0
        commodity.setStatus(1);
        commodity.setId(tbItem.getId());
        commodity.setPrice(tbItem.getPrice());
        commodity.setTitle(tbItem.getTitle());
        commodity.setImg(tbItem.getImage());
        //判断 购物车中 有没有传递过来的id
        for (Commodity commoditys : commodities) {
            //如果有  商品数量增加
            if (commoditys.getId().equals(itemId)) {
                if (num <= 0) {
                    commodities.remove(commoditys);
                } else if (tbItem.getNum() >= num && num > 0) {
                    commoditys.setAmount(num);
                } else if (tbItem.getNum() < num) {
                    commoditys.setAmount(tbItem.getNum());
                }

                return commodities;
            }
        }
        //如果没有  通过id 查询 接口
        if (num <= 0) {
            commodity.setAmount(1);
        } else if (tbItem.getNum() >= num) {
            commodity.setAmount(num);
        } else if (num >= tbItem.getNum()) {
            commodity.setAmount(tbItem.getNum());
        }
        //把查到的数据存到 commodity 中
        commodities.add(commodity);
        //存到 list 中,
        return commodities;
    }

    //把前段传递过来的数据存到redis中
    public List<Commodity> establishCart(Long itemId, Integer num, Long userId) {
        Jedis resource = jedisPool.getResource();
        //通过id 查询商品信息
        TbItem tbItem = findItemById(itemId);
        //new 一个商品对象
        Commodity commodity = new Commodity();
        //吧tbItem 中需要的数据存到 商品中
        commodity.setId(tbItem.getId());
        commodity.setPrice(tbItem.getPrice());
        commodity.setTitle(tbItem.getTitle());
        commodity.setStatus(1);
        if (num <= 0) {
            commodity.setAmount(1);
        } else if (tbItem.getNum() >= num) {
            commodity.setAmount(num);
        } else if (num >= tbItem.getNum()) {
            commodity.setAmount(tbItem.getNum());
        }
        commodity.setImg(tbItem.getImage());
        //吧商品对象转换为String 类型
        String string = JSON.toJSONString(commodity);
        //存入redis中
        resource.hset("用户id" + userId, "商品id" + itemId, string);
        //创建一个集合
        List<Commodity> commodityList = new ArrayList<>();
        //把商品存入集合中
        commodityList.add(commodity);
        //关流
        resource.close();
        //把集合返回给前段
        return commodityList;
    }

    @Override
    public List<Commodity> getCheckedCart(Long userId) {
        Jedis resource = jedisPool.getResource();
        Map<String, String> map = resource.hgetAll(CART_KEY_PREFIX + userId);
        resource.close();
        List<Commodity> commodityList = new ArrayList<>();
        for (String key : map.keySet()) {
            String value = map.get(key);
            Commodity commodity = JSON.parseObject(value, Commodity.class);
            if (commodity.getStatus() == 1) {
                commodityList.add(commodity);
            }
        }
        return commodityList;
    }

    @Override
    public List<Commodity> amendStatus(Integer status, Long userId, Long itemId) {
        Jedis resource = jedisPool.getResource();
        String hget = resource.hget(CART_KEY_PREFIX + userId, CART_FIELD_PREFIX + itemId);
        List<Commodity> commodityList = new ArrayList<>();
        Commodity parse = JSON.parseObject(hget, Commodity.class);
        if (parse.getId().equals(itemId)) {
            if (!parse.getStatus().equals(status)) {
                parse.setStatus(status);
                String string = JSON.toJSONString(parse);
                resource.hset(CART_KEY_PREFIX + userId, CART_FIELD_PREFIX + itemId, string);
                commodityList.add(parse);
            }
        }
        resource.close();
        return commodityList;
    }


    @Override
    public void cartDeletes(Long userId) {
        Jedis resource = jedisPool.getResource();
        resource.del(CART_KEY_PREFIX + userId);
        Map<String, String> map1 = resource.hgetAll(CART_KEY_PREFIX + userId);
        System.out.println(map1);
        resource.close();
    }

    @Override
    public void cartDle(Long userId, Long itemId) {
        Jedis resource = jedisPool.getResource();
        resource.hdel(CART_KEY_PREFIX + userId, CART_FIELD_PREFIX + itemId);
        resource.close();
    }

    @Override
    public List<Commodity> cartStatusAll(Long userId,Integer status) {
        Jedis resource = jedisPool.getResource();
        Map<String, String> map = resource.hgetAll(CART_KEY_PREFIX + userId);
        List<Commodity> commodityList = new ArrayList<>();
        for (String key : map.keySet()) {
            String value = map.get(key);
            Commodity commodity = JSON.parseObject(value, Commodity.class);
            if (status==1){
                commodity.setStatus(1);
            }else {
                commodity.setStatus(0);
            }
            commodityList.add(commodity);
            String string = JSON.toJSONString(commodity);
            resource.hset(CART_KEY_PREFIX + userId, key, string);
        }
        resource.close();
        return commodityList;
    }

    @Override
    public List<Commodity> loginMergeAll(Long userId, HttpServletRequest request) {
        Jedis resource = jedisPool.getResource();
        String cart = CookieUtils.getCookieValue(request, "cart", true);
        List<Commodity> commodityList2 = JSON.parseArray(cart, Commodity.class);
        assert commodityList2 != null;
        List<Commodity> commodityList = new ArrayList<>();
        for (Commodity commodity : commodityList2) {
            Map<String, String> map = resource.hgetAll(CART_KEY_PREFIX + userId);
            for (String key : map.keySet()) {
                String value = map.get(key);
                Commodity commodity1 = JSON.parseObject(value, Commodity.class);
                if (commodity1.getId().equals(commodity.getId())) {
                    commodity1.setAmount(commodity.getAmount() + commodity1.getAmount());
                } else {
                    String string = JSON.toJSONString(commodity);
                    resource.hset(CART_KEY_PREFIX + userId, CART_FIELD_PREFIX + commodity.getId(), string);
                }
                commodityList.add(commodity1);
            }
        }
//        Cookie[] cookies = request.getCookies();
//        for (Cookie cookie : cookies) {
//            if (cookie.getName().equals("cart")){
//                cookie.setMaxAge(0);
//                System.out.println(cookie.getMaxAge());
//            }
//        }
        return commodityList;
    }

    @Override
    public boolean cartDelete(HttpServletRequest request, HttpServletResponse response) {
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("cart")) {
                cookie.setMaxAge(0);
                response.addCookie(cookie);
                return true;
            }
        }
        return false;
    }

    @Override
    public void editCart(Long itemId, Integer num, Long userId) {
        Jedis jedis = jedisPool.getResource();
        String itemStr = jedis.hget(CART_KEY_PREFIX + userId, CART_FIELD_PREFIX + itemId);
        Commodity commodity = null;
        TbItem item = findItemById(itemId);
        if (itemStr != null) {
            commodity = JSON.parseObject(itemStr, Commodity.class);
            if (num <= 0) {
                commodity.setAmount(1);
            } else if (item.getNum() >= num) {
                commodity.setAmount(num);
            } else if (num >= item.getNum()) {
                commodity.setAmount(item.getNum());
            }
            ;
        } else {
            commodity = parseItemToCommodity(item, num);
        }
        String s = JSON.toJSONString(commodity);
        jedis.hset(CART_KEY_PREFIX + userId, CART_FIELD_PREFIX + itemId, s);
        jedis.close();
    }

    @Override
    public List<Commodity> getCartItemList(Long userId) {
        Jedis resource = jedisPool.getResource();
        Map<String, String> map = resource.hgetAll(CART_KEY_PREFIX + userId);
        resource.close();

        List<Commodity> commodityList = new ArrayList<>();
        for (String key : map.keySet()) {
            String value = map.get(key);
            Commodity commodity = JSON.parseObject(value, Commodity.class);
            commodityList.add(commodity);
        }

        return commodityList;
    }

    private TbItem findItemById(Long itemId) {
        System.out.println(itemId);
        //通过id查询接口 获取 数据 //把获取的数据转换为tbItem
        return HttpClientUtils.getObject(CAT_JSON_URL + itemId, TbItem.class);

    }

    private Commodity parseItemToCommodity(TbItem item, Integer num) {
        Commodity commodity = new Commodity();
        //吧tbItem 中需要的数据存到 商品中
        commodity.setId(item.getId());
        commodity.setPrice(item.getPrice());
        commodity.setTitle(item.getTitle());
        commodity.setStatus(1);
        if (num <= 0) {
            commodity.setAmount(1);
        } else if (item.getNum() >= num) {
            commodity.setAmount(num);
        } else if (num >= item.getNum()) {
            commodity.setAmount(item.getNum());
        }
        commodity.setImg(item.getImage());
        return commodity;
    }

}


